<script lang="ts" setup>
import {computed, defineProps} from 'vue';

interface PaginationProps {
  currentPage: number;
  totalPages: number;
  onPageChange?: (page: number) => void;
}

const props = defineProps<PaginationProps>();

const pageNumbers = computed(() => {
  const pages = [];
  const startPage = Math.max(1, props.currentPage - 2);
  const endPage = Math.min(props.totalPages, props.currentPage + 2);

  if (startPage > 2) {
    pages.push(1, '...');
  }

  for (let i = startPage; i <= endPage; i++) {
    pages.push(i);
  }

  if (endPage < props.totalPages - 1) {
    pages.push('...', props.totalPages);
  }

  return pages;
});

const handlePageChange = (page: number) => {
  if (page !== props.currentPage && props.onPageChange) {
    props.onPageChange(page);
  }
};

const getButtonClass = (pageNumber: number) => {
  if (props.currentPage === pageNumber || pageNumber <= 0 || pageNumber >= props.totalPages + 1) {
    return 'p_fun_d';
  } else {
    return 'p_fun';
  }
}
</script>

<template>
  <div class="flex justify-center items-center gap-2 mx-auto mt-4">
    <div
        :class="getButtonClass(1)"
        class="button"
        @click="props.currentPage !== 1 && handlePageChange(1)"
    >首页
    </div>

    <div
        :class="getButtonClass(props.currentPage - 1)"
        class="button"
        @click="props.currentPage > 1 && handlePageChange(props.currentPage - 1)"
    >上页
    </div>

    <div
        v-for="pageNumber in pageNumbers"
        :key="pageNumber"
        :class="{
        'p_no_d': pageNumber === props.currentPage,
        'p_dot': pageNumber === '...',
        'p_fun': pageNumber !== '...' && pageNumber !== props.currentPage
      }"
        class="button number-page"
        @click="pageNumber !== '...' && handlePageChange(Number(pageNumber))"
    >
      <template v-if="pageNumber === '...'">...</template>
      <template v-else>{{ pageNumber }}</template>
    </div>

    <div
        :class="getButtonClass(props.currentPage + 1)"
        class="button"
        @click="props.currentPage < props.totalPages && handlePageChange(props.currentPage + 1)"
    >下页
    </div>

    <div
        :class="getButtonClass(props.totalPages)"
        class="button"
        @click="props.currentPage !== props.totalPages && handlePageChange(props.totalPages)"
    >尾页
    </div>
  </div>
</template>

<style scoped>
.button {
  padding: 3px;
  background: transparent;
  cursor: pointer;
  width: 2.2rem;
  text-align: center;
}

.number-page {
  width: 1.5rem;
}

.p_fun {
  border: 1px solid #4e4e4e;
  color: #4e4e4e;
}

.p_no_d, .p_fun:hover {
  border: 1px solid #ff2323;
  color: #ff2323;
}

.p_fun_d {
  border: 1px solid #e3e3e3;
  color: #e3e3e3;
  cursor: default;
}

.p_no_d {
  cursor: default;
}

.p_dot {
  border: none;
}
</style>